<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;

class CommonController extends BaseController
{
    /**
     * CommonController constructor.
     */
    public function __construct()
    {
        $this->middleware('jwt.auth');
        $this->middleware('jwt.refresh');
    }

    /**
     * @param Request $request
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @return mixed
     */
    public function imageUpload(Request $request)
    {
        $fileField = 'lablog-image';
        if (!$request->hasFile($fileField)) {
            return $this->response->errorBadRequest('上传文件为空');
        }
        $file = $request->file($fileField);
        $validator = \Illuminate\Support\Facades\Validator::make(
            $request->all(),
            [
                $fileField => 'required|max:2048|image|dimensions:max_width=1920,max_height=1080',
            ]
        );
        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }
        if (!$file->isValid()) {
            return $this->response->errorBadRequest('文件上传出错');
        }
        $path = './' . trim('upload', './') . '/' . date('Ymd') . '/';
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        $oldName = $file->getClientOriginalName();
        $newName = 'image_' . time() . '_' . str_random(10) . '.png';
        if (!$file->move($path, $newName)) {
            return $this->response->errorInternal('保存文件失败', 500);
        }
        $filePath = trim($path, '.');
        $absolutePath = base_path('public/' . $filePath) . $newName;
        $publicPath = $filePath . $newName;

        return $this->response->array([
            'old_name' => $oldName,
            'new_name' => $newName,
            'path' => $filePath,
            'absolutePath' => $absolutePath,
            'publicPath' => $publicPath,
        ]);
    }
}
